import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import '/components/form/selectRadio.dart';
import '/components/form/treeSelect.dart';
import '/utils/api.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:owner_flutter/components/form/ImagePicker.dart';

class FormDemoPage extends StatefulWidget {
  const FormDemoPage({Key? key}) : super(key: key);

  @override
  _FormDemoPageState createState() => _FormDemoPageState();
}

class _FormDemoPageState extends State<FormDemoPage> {
  final _formKey = GlobalKey<FormBuilderState>();

  String _type = '';
  String _orgId = '';
  List _fileList = [];
  Future<bool> _onWillPop(context) async {
    //阻止误触退出表单页
    bool shouldClose = true;
    await showCupertinoDialog(
      context: context,
      builder: (context) => CupertinoAlertDialog(
        title: Text('确定离开吗?'),
        actions: <Widget>[
          CupertinoButton(
            child: Text('确定'),
            onPressed: () {
              shouldClose = true;
              Navigator.of(context).pop();
            },
          ),
          CupertinoButton(
            child: Text('取消'),
            onPressed: () {
              shouldClose = false;
              Navigator.of(context).pop();
            },
          ),
        ],
      ),
    );
    return shouldClose;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('常用表单'),
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(20),
        child: AnimationLimiter(
          child: Column(
            children: AnimationConfiguration.toStaggeredList(
              duration: const Duration(milliseconds: 1000),
              childAnimationBuilder: (widget) => SlideAnimation(
                horizontalOffset: 50.0,
                child: FadeInAnimation(
                  child: widget,
                ),
              ),
              children: <Widget>[
                TreeSelect(
                  title: '维修类目',
                  required: true,
                  loadUrl: Api.serviceTreeList,
                  multiple: false,
                  onChange: (val) => {_orgId = val},
                ),
                SelectRadio(
                  title: '采购类型',
                  required: true,
                  dictCode: 'purchase_type',
                  isDict: true,
                  onChange: (val) => {_type = val},
                ),
                SizedBox(height: 20),
                FormBuilder(
                  key: _formKey,
                  onWillPop: () => _onWillPop(context),
                  autovalidateMode: AutovalidateMode.onUserInteraction,
                  child: Column(
                    children: [
                      FormBuilderTextField(
                        name: 'textField',
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return '请输入';
                          }
                          return null;
                        },
                        decoration: InputDecoration(
                          border: OutlineInputBorder(),
                          labelText: "文本",
                        ),
                      ),
                      SizedBox(height: 20),
                      FormBuilderTextField(
                        name: 'estimatedAmount',
                        decoration: InputDecoration(
                          border: OutlineInputBorder(),
                          labelText: "预估采购金额",
                        ),
                        keyboardType: TextInputType.number, //限定数字键盘
                        inputFormatters: <TextInputFormatter>[
                          FilteringTextInputFormatter.digitsOnly
                        ], // Only numbers can be entered
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return '请输入预估金额';
                          }
                          return null;
                        },
                      ),
                      SizedBox(height: 20),
                      FormBuilderDateTimePicker(
                        decoration: InputDecoration(
                          border: OutlineInputBorder(),
                          labelText: "时间",
                        ),
                        name: 'dateTime',
                        resetIcon: Icon(Icons.close),
                        locale: Locale('zh'),
                        validator: (value) {
                          if (value == null) {
                            return '请选择时间';
                          }
                          return null;
                        },
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 20),
                ImagePicker(
                  required: true,
                  onChange: (val) => {_fileList = val},
                ),
                SizedBox(height: 20),
                CupertinoButton(
                  child: Text('提交'),
                  color: Theme.of(context).primaryColor,
                  pressedOpacity: .4, // 按下透明度
                  borderRadius: BorderRadius.circular(10),
                  onPressed: () {
                    print('orgid:$_orgId');
                    print(_type);
                    print('filelist:$_fileList');
                    print(_formKey.currentState);

                    final validateSuccess = _formKey.currentState!.validate();
                    if (validateSuccess) {
                      _formKey.currentState!.save();
                      final formData = _formKey.currentState!.value;
                      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                        content: Text('$formData'),
                      ));
                    }
                  },
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
